package cn.changeforyou.analyzer.xmlparse.mybatis.reader;

import cn.changeforyou.analyzer.combine.orm.XmlCodeType;
import cn.changeforyou.analyzer.xmlparse.mybatis.model.SqlLabel;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Node;
import org.dom4j.tree.DefaultElement;
import org.dom4j.tree.DefaultText;

public abstract class AbstractColumnListReaderWriter extends AbstractXmlLabelReaderWriter<SqlLabel> {
	
	
	
	@Override
	protected List<SqlLabel> read(List<Node> nodes) {
		List<SqlLabel> sqlLabels = new ArrayList<>();
		if(nodes.isEmpty()) {
			return sqlLabels;
		}
		Node node = nodes.get(0);
		if (node instanceof DefaultElement) {
			DefaultElement element = (DefaultElement) node;
			String id = element.attribute("id").getStringValue();
			if (!id.endsWith("Column_List")) {
				return sqlLabels;
			}
			SqlLabel sqlLabel = new SqlLabel();
			sqlLabels.add(sqlLabel);
			
			sqlLabel.setNode(element);
			sqlLabel.setId(XmlCodeType.valueOf(id));
			List<Node> content = element.content();
			if (!content.isEmpty()) {
				StringBuilder sb = new StringBuilder();
				for (Node fragment : content) {
					if (fragment instanceof DefaultText) {
						DefaultText text = (DefaultText) fragment;
						sb.append(text.getText().trim().replaceAll(",", ", ").replaceAll("\n", " ").replaceAll("\\s{2,}", " "));
					}
				}
				String sql = sb.toString();
				sqlLabel.setSql(sql);
				String[] split = sql.split(", ");
				List<SqlLabel.SqlField> sqlFields = new ArrayList<>();
				sqlLabel.setSqlFields(sqlFields);
				for (int i = 0; i < split.length; i++) {
					SqlLabel.SqlField sqlField = new SqlLabel.SqlField(sqlLabel);
					sqlFields.add(sqlField);
					String s1 = split[i];
					String[] split1 = s1.split(" as ");
					if (split1.length > 1) {
						//别名形式
						sqlField.setColumnName(split1[0]);
						sqlField.setAliasName(split1[1]);
					} else {
						sqlField.setColumnName(split1[0]);
					}
				}
			}
		}
		return sqlLabels;
	}
	
	@Override
	protected String getXpath() {
		return "/mapper/sql[@id]";
	}
}
